# -*- coding = utf-8 -*-
# @Time : 2024/6/9 18:08
# @Author : 0505200213石浪
# @File : login.py
# @Software : PyCharm


from flask import request, redirect, url_for, session, render_template
from . import bp
from db_operations import Database

db = Database()


# 登录页面
@bp.route('/login')
def login():
    return render_template("login.html")


# 退出
@bp.route('/quit/<username>')
def quit_login(username):
    session.pop(username)
    return render_template("login.html")


# 登录功能
@bp.route('/login', methods=['POST'])
def loginOP():
    username = request.form['username']
    password = request.form['password']
    user_type = request.form['userType']
    if user_type == 'user':
        sql = "SELECT * FROM movieFriends.user WHERE username=%s"
        user = db.execute(sql, (username,))
        if user:
            if password == user[0][2]:
                info = {'id': user[0][0], 'gender': user[0][3], 'age': user[0][4], 'signature': user[0][5],
                        'address': user[0][6], 'hobbies': user[0][7], 'avatar': user[0][8]}
                session[username] = info
                return redirect(url_for('main.home_page', username=username))
            else:
                return "密码错误，请重新输入"
        else:
            return "身份错误或用户不存在，请注册"
    elif user_type == 'manager':
        sql = "SELECT * FROM movieFriends.manager WHERE manager_name=%s"
        manager = db.execute(sql, (username,))
        if password == manager[0][2]:
            return redirect(url_for('main.manage_movie'))
        else:
            return "密码错误，请重新输入"


# 注册页面
@bp.route('/register')
def register():
    return render_template("register.html")


# 注册逻辑
@bp.route('/register', methods=['POST'])
def registerOP():
    username = request.form['username']
    password = request.form['password']
    sql_check_username = "SELECT * FROM movieFriends.user WHERE username=%s"
    existing_user = db.execute(sql_check_username, (username,))
    if existing_user:
        return "用户名已存在，请选择其他用户名。"
    if len(username) > 10:
        return "用户名长度不能超过10个字符，请重新输入。"
    if not password.isdigit() or len(password) != 6:
        return "密码必须为6位数字，请重新输入。"
    sql_insert_user = "INSERT INTO movieFriends.user (username, password, Avatar) VALUES (%s, %s, %s)"
    db.execute(sql_insert_user, (username, password, '../static/assets/img/Avatar/头像默认.png'))
    return "注册成功！请返回登录"
